package org.example.aienglishapp.service.speech.sentence;

import org.example.aienglishapp.entity.speech.sentence.Sentence;
import org.example.aienglishapp.mapper.speech.sentence.SentenceMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class SentenceService {

    private static final Logger logger = LoggerFactory.getLogger(SentenceService.class);

    @Autowired
    private SentenceMapper sentenceMapper;

    @Transactional(readOnly = true)
    public Sentence findById(Long id) {
        return sentenceMapper.findById(id);
    }

    @Transactional(readOnly = true)
    public List<Sentence> findAll() {
        return sentenceMapper.findAll();
    }

    @Transactional(rollbackFor = {IOException.class})
    public int insertSentence(Sentence sentence, MultipartFile audioFile) throws IOException {
        try {
            if (!audioFile.isEmpty()) {
                byte[] audioBytes = audioFile.getBytes();  // 直接获取文件的字节数据
                sentence.setAudio(audioBytes);  // 存储字节数组
            }
            return sentenceMapper.insert(sentence);
        } catch (IOException e) {
            logger.error("Error processing audio file for sentence insertion: {}", e.getMessage(), e);
            throw e; // 重新抛出异常以便触发事务回滚
        }
    }

    // 更新句子信息（写事务，默认会回滚未检查异常）
    @Transactional(rollbackFor = {IOException.class})
    public int updateSentence(Sentence sentence, MultipartFile audioFile) throws IOException {
        try {
            if (audioFile != null && !audioFile.isEmpty()) {
                byte[] audioBytes = audioFile.getBytes();  // 直接获取文件的字节数据
                sentence.setAudio(audioBytes);  // 存储字节数组
            }
            return sentenceMapper.update(sentence);
        } catch (IOException e) {
            logger.error("Error processing audio file for sentence update: {}", e.getMessage(), e);
            throw e; // 重新抛出异常以便触发事务回滚
        }
    }

    @Transactional
    public int deleteById(Long id) {
        return sentenceMapper.deleteById(id);
    }

    @Transactional(readOnly = true)
    public List<Sentence> findByChapterId(Long chapterId) {
        return sentenceMapper.findByChapterId(chapterId);
    }
}

